package skuorder

import (
	"encoding/json"
	"strconv"
	"oxy_server/model"
	"oxy_server/module/log"
	"oxy_server/until"
	"time"

	"github.com/labstack/echo"
	"gopkg.in/mgo.v2/bson"
)

type (
	Skuorder struct {
		ID                     bson.ObjectId `json:"_id" bson:"_id"`
		ProductID              string        `json:"productid" bson:"productid"`
		ProductctionGroupID    string        `json:"productctiongroupid" bson:"productctiongroupid"`
		SkuCode                string        `json:"skucode" bson:"skucode"`
		SkuDesc                string        `json:"skudesc" bson:"skudesc"`
		ClothingSupplier       string        `json:"clothingsupplier" bson:"clothingsupplier"`
		WatermarkNumber        string        `json:"watermarknumber" bson:"watermarknumber"`
		WatermarkSupplier      string        `json:"watermarksupplier" bson:"watermarksupplier"`
		WatermarkSingleMoney   string        `json:"watermarksinglemoney" bson:"watermarksinglemoney"`
		CertificateNumber      string        `json:"certificatenumber" bson:"certificatenumber"`
		CertificateSupplier    string        `json:"certificatesupplier" bson:"certificatesupplier"`
		CertificateSingleMoney string        `json:"certificatesinglemoney" bson:"certificatesinglemoney"`
		SizemarkNumber         string        `json:"sizemarknumber" bson:"sizemarknumber"`
		SizemarkSupplier       string        `json:"sizemarksupplier" bson:"sizemarksupplier"`
		SizemarkSingleMoney    string        `json:"sizemarksinglemoney" bson:"sizemarksinglemoney"`
		Count                  string        `json:"count" bson:"count"`
		OrderCount             string        `json:"ordercount" bson:"ordercount"`
		Cost                   string        `json:"cost" bson:"cost"`
		OrderTime              string        `json:"ordertime" bson:"ordertime"`
		Time                   string        `json:"time" bson:"time"`
		SkuList                string        `json:"skulist" bson:"skulist"`
		Fabriccost             string        `json:"fabriccost" bson:"fabriccost"`
		Fabrictotal            string        `json:"fabrictotal" bson:"fabrictotal"`
		Feathercost            string        `json:"feathercost" bson:"feathercost"`
		Feathertotal           string        `json:"feathertotal" bson:"feathertotal"`
		Fabricsupplier         string        `json:"fabricsupplier" bson:"fabricsupplier"`
		Feathersupplier        string        `json:"feathersupplier" bson:"feathersupplier"`
		Factorymodelnumber     string        `json:"factorymodelnumber" bson:"factorymodelnumber"`
		IsEdiet                bool          `json:"isedit" bson:"isedit"`
		ContractStatus         string        `json:"contractstatus" bson:"contractstatus"`
		Contract               string        `json:"contract" bson:"contract"`
		Brand                  string        `json:"brand" bson:"brand"`
		Picture                []string      `json:"picture" bson:"picture"`
		SkuOrder               []OrderInfo   `json:"skuorder" bson:"skuorder"` // 1203 add 格式化订单详细信息
	}
	insertskuorder struct {
		ProductID              string      `json:"productid" bson:"productid"`
		ProductctionGroupID    string      `json:"productctiongroupid" bson:"productctiongroupid"`
		SkuCode                string      `json:"skucode" bson:"skucode"`
		SkuDesc                string      `json:"skudesc" bson:"skudesc"`
		ClothingSupplier       string      `json:"clothingsupplier" bson:"clothingsupplier"`
		WatermarkNumber        string      `json:"watermarknumber" bson:"watermarknumber"`
		WatermarkSupplier      string      `json:"watermarksupplier" bson:"watermarksupplier"`
		WatermarkSingleMoney   string      `json:"watermarksinglemoney" bson:"watermarksinglemoney"`
		CertificateNumber      string      `json:"certificatenumber" bson:"certificatenumber"`
		CertificateSupplier    string      `json:"certificatesupplier" bson:"certificatesupplier"`
		CertificateSingleMoney string      `json:"certificatesinglemoney" bson:"certificatesinglemoney"`
		SizemarkNumber         string      `json:"sizemarknumber" bson:"sizemarknumber"`
		SizemarkSupplier       string      `json:"sizemarksupplier" bson:"sizemarksupplier"`
		SizemarkSingleMoney    string      `json:"sizemarksinglemoney" bson:"sizemarksinglemoney"`
		Count                  string      `json:"count" bson:"count"`
		OrderCount             string      `json:"ordercount" bson:"ordercount"`
		Cost                   string      `json:"cost" bson:"cost"`
		OrderTime              string      `json:"ordertime" bson:"ordertime"`
		Time                   string      `json:"time" bson:"time"`
		SkuList                string      `json:"skulist" bson:"skulist"`
		Fabriccost             string      `json:"fabriccost" bson:"fabriccost"`
		Fabrictotal            string      `json:"fabrictotal" bson:"fabrictotal"`
		Feathercost            string      `json:"feathercost" bson:"feathercost"`
		Feathertotal           string      `json:"feathertotal" bson:"feathertotal"`
		Fabricsupplier         string      `json:"fabricsupplier" bson:"fabricsupplier"`
		Feathersupplier        string      `json:"feathersupplier" bson:"feathersupplier"`
		Factorymodelnumber     string      `json:"factorymodelnumber" bson:"factorymodelnumber"`
		IsEdiet                bool        `json:"isedit" bson:"isedit"`
		ContractStatus         string      `json:"contractstatus" bson:"contractstatus"`
		Contract               string      `json:"contract" bson:"contract"`
		Brand                  string      `json:"brand" bson:"brand"`
		Picture                []string    `json:"picture" bson:"picture"`
		SkuOrder               []OrderInfo `json:"skuorder" bson:"skuorder"` // 1203 add 格式化订单详细信息
	}
	OrderInfo struct {
		SkuDesc    string `json:"skudesc" bson:"skudesc"`
		SkuCode    string `json:"skucode" bson:"skucode"`
		Count      string `json:"count" bson:"count"`
		OrderCount string `json:"ordercount" bson:"ordercount"`
	}
	Updatesku struct {
		OldSkuCode string `json:"oldskucode" bson:"skucode"`
		NewSkuCode string `json:"newskucode" bson:"skucode"`
	}
)

type OXYSkuOrder struct{}

func NewOXYSkuOrder() *OXYSkuOrder {
	Data := &OXYSkuOrder{}
	return Data
}

func (v2 *OXYSkuOrder) GetSkuOrderListHandler(c echo.Context) error {
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	jsonquery := c.QueryParam("like")
	sort := c.QueryParam("sort")
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "sku_order"
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, count, err := model.DB().QuerySort(M, currentpage, perpage, sort)
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []Skuorder{}
	query.All(&ps)

	str, err := json.Marshal(ps)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  string(str),
		"count": count,
	})

	return nil
}

func (v2 *OXYSkuOrder) AddSkuOrderHandler(c echo.Context) error {
	log.Info("AddSkuOrderHandlerNew")
	s := &insertskuorder{}
	if err := c.Bind(s); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "sku_order"
	err := model.DB().Insert(s)
	if err != nil {
		log.Error("插入出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	skuorderList := []Skuorder{}
	queryorder, _, err := model.DB().Query(bson.M{"productid": s.ProductID}, 0, 0)
	if err != nil {
		log.Error("计算产品下单数入库数出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	queryorder.All(&skuorderList)

	OrderCount := 0
	Count := 0
	for _, order := range skuorderList {
		orderCount, _ := strconv.Atoi(order.OrderCount)
		count, _ := strconv.Atoi(order.Count)
		OrderCount += orderCount
		Count += count
	}
	orderStatus := 0
	if len(skuorderList) == 1 {
		orderStatus = 1
	} else if len(skuorderList) > 1 {
		orderStatus = 2
	}
	// 新建订单时更新生产组的入库时间
	InboundDate := until.FormatTime(s.Time)
	h, _ := time.ParseDuration("1h")
	InboundDate = InboundDate.Add(8 * h)
	model.DB().Document = "product_plan"
	selector := bson.M{"_id": bson.ObjectIdHex(s.ProductID)}
	data := bson.M{"$set": bson.M{"inbounddate": InboundDate, "ordercount": OrderCount, "count": Count, "orderstatus": orderStatus, "targetprice": s.Cost}}
	err = model.DB().Update(selector, data)
	if err != nil {
		log.Error("更新出错，生产组最新入库时间", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

func (v2 *OXYSkuOrder) UpdateSkuOrderHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("UpdateSkuOrderHandler", id)
	s := &insertskuorder{}
	if err := c.Bind(s); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "sku_order"
	err := model.DB().Update(bson.M{"_id": bson.ObjectIdHex(id)}, s)
	if err != nil {
		log.Error("更新出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	skuorderList := []Skuorder{}
	queryorder, _, err := model.DB().Query(bson.M{"productid": s.ProductID}, 0, 0)
	if err != nil {
		log.Error("计算产品下单数入库数出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	queryorder.All(&skuorderList)
	OrderCount := 0
	Count := 0
	for _, order := range skuorderList {
		orderCount, _ := strconv.Atoi(order.OrderCount)
		count, _ := strconv.Atoi(order.Count)
		OrderCount += orderCount
		Count += count
	}
	orderStatus := 0
	if len(skuorderList) == 1 {
		orderStatus = 1
	} else if len(skuorderList) > 1 {
		orderStatus = 2
	}
	// 更新订单时更新生产组的入库时间
	InboundDate := until.FormatTime(s.Time)
	h, _ := time.ParseDuration("1h")
	InboundDate = InboundDate.Add(8 * h)
	model.DB().Document = "product_plan"
	log.Info("targetprice:", s.Cost)
	selector := bson.M{"_id": bson.ObjectIdHex(s.ProductID)}
	data := bson.M{"$set": bson.M{"inbounddate": InboundDate, "ordercount": OrderCount, "count": Count, "orderstatus": orderStatus, "targetprice": s.Cost}}
	err = model.DB().Update(selector, data)
	if err != nil {
		log.Error("更新出错，生产组最新入库时间", err)
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

func (v2 *OXYSkuOrder) DelSkuOrderHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("DelSkuOrderHandler", id)
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "sku_order"
	s := insertskuorder{}
	query, _ := model.DB().QueryOne(bson.M{"_id": bson.ObjectIdHex(id)})
	query.One(&s)

	err := model.DB().Remove(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		log.Error("删除出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	skuorderList := []Skuorder{}
	queryorder, _, err := model.DB().Query(bson.M{"productid": s.ProductID}, 0, 0)
	if err != nil {
		log.Error("计算产品下单数入库数出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	queryorder.All(&skuorderList)
	OrderCount := 0
	Count := 0
	for _, order := range skuorderList {
		orderCount, _ := strconv.Atoi(order.OrderCount)
		count, _ := strconv.Atoi(order.Count)
		OrderCount += orderCount
		Count += count
	}
	orderStatus := 0
	if len(skuorderList) == 1 {
		orderStatus = 1
	} else if len(skuorderList) > 1 {
		orderStatus = 2
	}
	// 更新订单时更新生产组的下单数目和入库数目
	model.DB().Document = "product_plan"
	selector := bson.M{"_id": bson.ObjectIdHex(s.ProductID)}
	data := bson.M{"$set": bson.M{"ordercount": OrderCount, "count": Count, "orderstatus": orderStatus, "targetprice": "0"}}
	err = model.DB().Update(selector, data)
	if err != nil {
		log.Error("更新出错v2，生产组最新入库时间", err)
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})
	return nil
}

func (v2 *OXYSkuOrder) UpdateSkuOrderInfo(c echo.Context) error {
	data := []Updatesku{}
	if err := c.Bind(&data); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "sku_order"
	query, _, err := model.DB().QuerySort(nil, 0, 0, "_id")
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []Skuorder{}
	query.All(&ps)
	SkuCodeMap := make(map[string]string)
	for _, d := range data {
		SkuCodeMap[d.OldSkuCode] = d.NewSkuCode
	}
	log.Info("SkuCodeMap", SkuCodeMap)
	for _, v := range ps {
		orderinfo := v.SkuOrder
		// err = json.Unmarshal([]byte(v.SkuList), &orderinfo)
		// if err != nil {
		// 	log.Error("解析下单信息错误", err)
		// }
		flag := false
		if len(orderinfo) > 0 {
			flag = true
			for i, o := range orderinfo {
				if skucode, ok := SkuCodeMap[o.SkuCode]; ok {
					orderinfo[i].SkuCode = skucode
				}
			}
		}
		if flag {
			model.DB().Document = "sku_order"
			err := model.DB().Update(bson.M{"_id": v.ID}, bson.M{"$set": bson.M{"skuorder": orderinfo}})
			if err != nil {
				log.Error("更新下单信息出错", err)
			}
		}
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})
	return nil
}
